<template>
  <div class="app-container">
    <div class="contract-search">
      <h1>从文件发起合同</h1>
    </div>


    <div>
      <el-form style="width: 600px">
        <el-form-item label="上传文件">
          <el-upload
            class="upload-demo"
            ref="upload"
            :multiple="false"
            drag
            :limit="100"
            :file-list="fileList"
            action="#"
            :http-request="executeUpload"
            :auto-upload="false"
            :before-upload="beforeExcelUpload"
            :on-change="onUploadChange"
            :before-remove="onRemoveItem"
            accept=".pdf"
            :show-file-list="false"
          >
            <div v-if="fileList.length > 0" style="margin-top: 50px;width: 100%">
              <ul class="el-upload-list el-upload-list--text">
                <li tabindex="0" class="el-upload-list__item is-ready" v-for="file in fileList" :key="file.name">
                  <a class="el-upload-list__item-name"><i class="el-icon-document"></i>{{file.name}}</a>
                  <label class="el-upload-list__item-status-label"><i class="el-icon-upload-success el-icon-circle-check"></i></label>
                  <label>文件大小：{{bytesToSize(file.size)}}</label>
                </li>
              </ul>
              <div class="el-upload__text"><em>重新上传</em><span style="display: inline-block;width: 20px;"></span><em @click.stop="deleteFile">删除</em></div>
            </div>
            <template v-else>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </template>
            <div class="el-upload__tip" slot="tip">文件最大支持100M，支持pdf格式文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="个人签署方姓名">
          <el-input v-model="approverName" type="text" />
        </el-form-item>
        <el-form-item label="个人签署方手机号">
          <el-input v-model="approverMobile" type="text" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmitUpload">确定提交并发起</el-button>
      </span>
    </div>

    <el-dialog
      title="签署链接"
      :visible.sync="dialogVisible"
      >

      <div style="text-align: center">
        <h2>请使用微信扫描下方二维码</h2>
        <div>
          <img :width="200" :height="200" :src="schemeQrCodeImg"/>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import qrcode from 'qrcode';
import { signContractByFile, createSchemaUrl } from '@/api/contract';


export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger',
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      fileList: [],
      uploadList: [],
      approverName: '',
      approverMobile: '',
      dialogVisible: false,
      schemeQrCodeImg: ''
      // 设置合同类型
    };
  },
  created() {
  },
  methods: {
    deleteFile() {
      this.fileList = [];
      this.uploadList = [];
    },
    onRemoveItem(info) {
      this.uploadList = this.uploadList.filter(item => item.uid !== info.uid);
    },
    beforeExcelUpload() {},
    createSchemaUrl({ flowId }) {
      createSchemaUrl({ flowId }).then((res) => {
        qrcode.toDataURL(res.data.SchemeUrl, (err, url) => {
          this.schemeQrCodeImg = url;
          this.dialogVisible = true;
        })
      });
    },
    executeUpload() {
      const promises = [];

      const toBase64Promise = item => new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(item.raw);
        reader.onload = (e) => {
          resolve({
            FileBody: e.target.result.split(',')[1],
            FileName: item.name,
          });
        };
        reader.onerror = (err) => {
          console.log(err);
          reject();
        };
      });

      this.uploadList.map((item) => {
        promises.push(toBase64Promise(item));
      });

      Promise.all(promises).then((results) => {
        signContractByFile({
          BusinessType: 'TEMPLATE',
          FileInfos: results,
          approverName: this.approverName,
          approverMobile: this.approverMobile,
        })
          .then((res) => {
            if (res.data.FlowId) {
              this.$confirm('发起合同成功, 是否获取签署链接?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info',
              }).then(() => {
                this.createSchemaUrl({
                  flowId: res.data.FlowId,
                });
              });
            }
          })
          .catch(e => console.log(e));
      });
    },
    onUploadChange(file, fileList) {
      // 判断 > 1M
      // 判断重名文件
      const repeatJudge = this.fileList.find(item => item.name === file.name);
      if (repeatJudge) {
        fileList.pop();
        // let msgRepeat = `您上传的${file.name}，该文件有重名文件，请您重新上传。`;
        return false;
      }
      this.fileList = [file];
      this.uploadList = [file];
    },
    onSubmitUpload() {
      if (!this.uploadList.length) {
        this.$message('请选择一个文件');
        return;
      }
      this.$refs.upload.submit();
    },
    bytesToSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'M', 'G'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return (bytes / Math.pow(k, i)).toPrecision(3) + '' + sizes[i];
    },
  }
};
</script>

<style lang="scss">
.contract-search {
  display: flex;
  justify-content: space-between;
  .contract-btns {
    position: relative;
    margin-bottom: 20px;
  }
}

.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
}
</style>
